from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from apps.accounts.models import UserProfile


class Command(BaseCommand):
    help = '为现有用户创建UserProfile'

    def handle(self, *args, **options):
        users_without_profile = []
        
        for user in User.objects.all():
            try:
                # 尝试访问用户的profile
                profile = user.userprofile
                self.stdout.write(
                    self.style.SUCCESS(f'用户 {user.username} 已有UserProfile')
                )
            except UserProfile.DoesNotExist:
                # 如果没有profile，创建一个
                UserProfile.objects.create(
                    user=user,
                    is_admin=(user.is_superuser or user.is_staff),
                    college='未设置',
                    phone='',
                    department='未设置'
                )
                users_without_profile.append(user.username)
                self.stdout.write(
                    self.style.SUCCESS(f'为用户 {user.username} 创建了UserProfile')
                )
        
        if users_without_profile:
            self.stdout.write(
                self.style.SUCCESS(
                    f'成功为 {len(users_without_profile)} 个用户创建了UserProfile: '
                    f'{", ".join(users_without_profile)}'
                )
            )
        else:
            self.stdout.write(
                self.style.SUCCESS('所有用户都已有UserProfile')
            )